/*********************
 *      INCLUDES
 *********************/

#include <rtthread.h>
#include <rtdevice.h>
#include "littlevgl2rtt.h"
#include "lvgl.h"
#include "lvsf_comp.h"
#include "gui_app_fwk.h"
#include "lv_ext_resource_manager.h"
#include "lv_ex_data.h"
#include "app_mem.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*********************
 *      DEFINES
 *********************/
#define APP_ID "calculator"

// 按钮尺寸和间距
#define BTN_SIZE 70
#define BTN_SPACING 10
#define DISPLAY_HEIGHT 70

// 声明图标
LV_IMG_DECLARE(calculator);

/*********************
 *  STATIC VARIABLES
 *********************/
static lv_obj_t *main_cont = NULL;
static lv_obj_t *display_label = NULL;

// 计算器状态
static char display_buffer[32] = "0";
static double num1 = 0;
static double num2 = 0;
static char operation = 0;
static bool new_input = true;
static bool has_dot = false;

/*********************
 *  STATIC PROTOTYPES
 *********************/
static void create_calculator_ui(void);
static void calc_btn_event_cb(lv_event_t *e);
static void update_display(void);
static void calculate_result(void);
static void reset_calculator(void);
static int32_t calculator_keypad_handler(lv_key_t key, lv_indev_state_t event);

/*********************
 *   GLOBAL FUNCTIONS
 *********************/

static void create_calculator_ui(void)
{
    // 创建主容器
    main_cont = lv_obj_create(lv_scr_act());
    lv_obj_set_size(main_cont, 370, 430);
    lv_obj_align(main_cont, LV_ALIGN_CENTER, 0, 0);
    lv_obj_set_style_bg_color(main_cont, lv_color_black(), LV_PART_MAIN);
    lv_obj_set_style_border_width(main_cont, 0, LV_PART_MAIN);

    // 创建显示区域
    lv_obj_t *display_area = lv_obj_create(main_cont);
    lv_obj_set_size(display_area, 370, DISPLAY_HEIGHT);
    lv_obj_align(display_area, LV_ALIGN_TOP_MID, 0, 20);
    lv_obj_set_style_bg_color(display_area, lv_color_make(0x20, 0x20, 0x20), LV_PART_MAIN);
    lv_obj_set_style_border_width(display_area, 2, LV_PART_MAIN);
    lv_obj_set_style_border_color(display_area, lv_color_make(0x40, 0x40, 0x40), LV_PART_MAIN);
    lv_obj_set_style_pad_all(display_area, 10, LV_PART_MAIN);
    lv_obj_set_style_radius(display_area, 5, LV_PART_MAIN);

    // 创建显示标签
    display_label = lv_label_create(display_area);
    lv_label_set_text(display_label, display_buffer);
    lv_obj_set_style_text_align(display_label, LV_TEXT_ALIGN_RIGHT, LV_PART_MAIN);
    lv_ext_set_local_font(display_label, FONT_BIGL, LV_COLOR_WHITE);
    lv_obj_align(display_label, LV_ALIGN_RIGHT_MID, -10, 0);

    // 按钮布局和颜色定义
    const char *btn_map[4][4] = {
        {"C", "7", "8", "9"},
        {"/", "4", "5", "6"},
        {"*", "1", "2", "3"},
        {"-", "+", "0", "="}
    };

    lv_color_t btn_colors[4][4] = {
        {lv_color_make(0x80, 0x80, 0x80), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40)},
        {lv_color_make(0xFF, 0x80, 0x00), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40)},
        {lv_color_make(0xFF, 0x80, 0x00), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0x40, 0x40, 0x40)},
        {lv_color_make(0xFF, 0x80, 0x00), lv_color_make(0xFF, 0x80, 0x00), lv_color_make(0x40, 0x40, 0x40), lv_color_make(0xFF, 0x80, 0x00)}
    };

    // 创建按钮网格
    int start_y = DISPLAY_HEIGHT + 40;
    int start_x = (370 - (BTN_SIZE * 4 + BTN_SPACING * 3)) / 2;
    
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            lv_obj_t *btn = lv_btn_create(main_cont);
            lv_obj_set_size(btn, BTN_SIZE, BTN_SIZE);
            lv_obj_align(btn, LV_ALIGN_TOP_LEFT, start_x + col * (BTN_SIZE + BTN_SPACING), start_y + row * (BTN_SIZE + BTN_SPACING));
            lv_obj_set_style_bg_color(btn, btn_colors[row][col], LV_PART_MAIN);
            lv_obj_set_style_radius(btn, 10, LV_PART_MAIN);
            lv_obj_set_style_shadow_width(btn, 5, LV_PART_MAIN);
            lv_obj_set_style_shadow_ofs_y(btn, 2, LV_PART_MAIN);
            
            lv_obj_t *label = lv_label_create(btn);
            lv_label_set_text(label, btn_map[row][col]);
            lv_ext_set_local_font(label, FONT_NORMAL, LV_COLOR_WHITE);
            lv_obj_center(label);
            lv_obj_add_event_cb(btn, calc_btn_event_cb, LV_EVENT_CLICKED, (void*)btn_map[row][col]);
        }
    }
}

static void calc_btn_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    if (code == LV_EVENT_CLICKED) {
        const char *btn_text = (const char *)lv_event_get_user_data(e);
        
        // 数字按钮 0-9
        if (btn_text[0] >= '0' && btn_text[0] <= '9' && btn_text[1] == '\0') {
            if (new_input) {
                strcpy(display_buffer, btn_text);
                new_input = false;
            } else if (strlen(display_buffer) < 15) {
                if (display_buffer[0] == '0' && !has_dot && strlen(display_buffer) == 1) {
                    strcpy(display_buffer, btn_text);
                } else {
                    strcat(display_buffer, btn_text);
                }
            }
        }
        // 清除按钮
        else if (strcmp(btn_text, "C") == 0) {
            reset_calculator();
        }
        // 运算符
        else if (strcmp(btn_text, "+") == 0 || strcmp(btn_text, "-") == 0 || 
                 strcmp(btn_text, "*") == 0 || strcmp(btn_text, "/") == 0) {
            num1 = atof(display_buffer);
            operation = btn_text[0];
            new_input = true;
            has_dot = false;
        }
        // 等号
        else if (strcmp(btn_text, "=") == 0) {
            if (operation != 0) {
                num2 = atof(display_buffer);
                calculate_result();
                operation = 0;
                new_input = true;
                has_dot = (strchr(display_buffer, '.') != NULL);
            }
        }
        
        update_display();
    }
}

static void update_display(void)
{
    lv_label_set_text(display_label, display_buffer);
    lv_obj_align(display_label, LV_ALIGN_RIGHT_MID, -5, 0);
}

static void calculate_result(void)
{
    double result = 0;
    
    switch (operation) {
        case '+': result = num1 + num2; break;
        case '-': result = num1 - num2; break;
        case '*': result = num1 * num2; break;
        case '/': 
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                strcpy(display_buffer, "Error");
                return;
            }
            break;
    }
    
    snprintf(display_buffer, sizeof(display_buffer), "%.10g", result);
}

static void reset_calculator(void)
{
    strcpy(display_buffer, "0");
    num1 = 0;
    num2 = 0;
    operation = 0;
    new_input = true;
    has_dot = false;
}

/*********************
 *   APP LIFECYCLE
 *********************/

static void on_start(void)
{
    lv_ext_set_locale(NULL, "zh_cn");
    create_calculator_ui();
    lv_img_cache_invalidate_src(NULL);
}

static void on_pause(void)
{
    // 暂停时无需特殊处理
}

static void on_resume(void)
{
    // 恢复时无需特殊处理
}

static void on_stop(void)
{
    if(main_cont) {
        lv_obj_del(main_cont);
        main_cont = NULL;
    }
}

static void msg_handler(gui_app_msg_type_t msg, void *param)
{
    switch (msg)
    {
    case GUI_APP_MSG_ONSTART: on_start(); break;
    case GUI_APP_MSG_ONRESUME: on_resume(); break;
    case GUI_APP_MSG_ONPAUSE: on_pause(); break;
    case GUI_APP_MSG_ONSTOP: on_stop(); break;
    default: break;
    }
}

static int app_main(intent_t i)
{
    gui_app_regist_msg_handler(APP_ID, msg_handler);
    return 0;
}

BUILTIN_APP_EXPORT(LV_EXT_STR_ID(calculator), LV_EXT_IMG_GET(calculator), APP_ID, app_main);